import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import "./Crumbs.css";
import {
  push_crumb_by_location,
  remove_crumb_by_path,
} from "../../utils/redux/slices/crumbSlice";
import { Tag } from "antd";
import { CloseOutlined } from "@ant-design/icons";
import url from "../../utils/url";

function Crumbs() {
  const location = useLocation();
  const { crumbs } = useSelector((d) => d.crumbs);
  const dispatch = useDispatch();
  const navigator = useNavigate();

  const handleClose = (path) => {
    dispatch(remove_crumb_by_path(path));
    if (url.isSamePath(path, location.pathname)) {
      navigator(crumbs.filter((d) => d.path != path)[crumbs.length - 2].path);
    }
  };
  const handleClick = (path) => {
    if (!url.isSamePath(path, location.pathname)) navigator(path);
  };
  useEffect(() => {
    dispatch(push_crumb_by_location(location));
    return () => {};
  }, [location]);
  return (
    <div className="crumb-list">
      {crumbs.map((d, i) => (
        <Tag
          className="tag"
          key={i}
          color={url.isSamePath(d.path, location.pathname) ? "processing" : ""}
          closeIcon={crumbs.length > 1 ? <CloseOutlined /> : ""}
          onClose={(e) => {
            e.preventDefault();
            handleClose(d.path);
          }}
          onClick={() => handleClick(d.path)}
        >
          {d.name}
        </Tag>
      ))}
    </div>
  );
}

export default Crumbs;
